package com.gitee.clarence.swagger;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.gitee.clarence.entity.SwaggerDoc;
import com.gitee.clarence.swagger.properties.SwaggerProperties;

import io.swagger.models.Contact;
import io.swagger.models.License;

/**
 * Created by IntelliJ IDEA. User: luopeng Date: 2017-07-17 下午4:13
 */
@Configuration
public class ConfigSwaggerDoc implements ImportAware, BeanClassLoaderAware {


    @Autowired
    private Environment environment;
	
	private ClassLoader classLoader;

	@Bean
	@ConditionalOnProperty(name = "swagger.enabled", havingValue = "true")
	public SwaggerSourceParse swaggerSourceParse() {
		return new SwaggerSourceParse();
	}

	@Bean
	@ConditionalOnProperty(name = "swagger.enabled", havingValue = "true")
	public SwaggerController swaggerController() {
		return new SwaggerController();
	}

	@Bean
	@ConditionalOnMissingBean
	public SwaggerProperties swaggerProperties() {
		return new SwaggerProperties();
	}

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnProperty(name = "swagger.enabled", havingValue = "true")
	public SwaggerDoc swaggerDoc() {

		SwaggerProperties swaggerProperties = defaultProperties(swaggerProperties());

		String host = swaggerProperties.getHost();
		String port = environment.getProperty("server.port");
		if(StringUtils.isNotBlank(port)){
			host+=":"+port;
		}
		if(!StringUtils.contains(host, "/")){
			String contextPath = environment.getProperty("server.servlet.context-path");
			if(StringUtils.isNotBlank(contextPath)){
				host+=contextPath;
			}
		}
		return new SwaggerDoc.SwaggerDocBuilder()//
				.addSkipAnnotations(SessionAttribute.class)//
				.withDoc("doc").withDoc("测试文档")//
				.withInfo(swaggerProperties).withHost(host)//
				.addIgnoreControllers("swaggerController", "basicErrorController")//
				.build();
	}

	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;

	}

	@Override
	public void setImportMetadata(AnnotationMetadata annotationMetadata) {
		Map<String, Object> enableAttrMap = annotationMetadata
				.getAnnotationAttributes(EnableSwaggerDoc.class.getName());
		AnnotationAttributes enableAttrs = AnnotationAttributes.fromMap(enableAttrMap);
		if (enableAttrs == null) {
			// search parent classes
			Class<?> currentClass = ClassUtils.resolveClassName(annotationMetadata.getClassName(), classLoader);
			for (Class<?> classToInspect = currentClass; classToInspect != null; classToInspect = classToInspect
					.getSuperclass()) {
				EnableSwaggerDoc enableDemo = AnnotationUtils.findAnnotation(classToInspect, EnableSwaggerDoc.class);
				if (enableDemo == null) {
					continue;
				}
				enableAttrMap = AnnotationUtils.getAnnotationAttributes(enableDemo);
				enableAttrs = AnnotationAttributes.fromMap(enableAttrMap);
			}
		}
		// this.closeProfiles = enableAttrs.getStringArray("closeProfiles");
	}
	
	
	private SwaggerProperties defaultProperties(SwaggerProperties swaggerProperties) {
		
		swaggerProperties.setEnabled(true);
		if(StringUtils.isBlank(swaggerProperties.getTitle())){
			swaggerProperties.setTitle("API文档");
		}
		if(StringUtils.isBlank(swaggerProperties.getDescription())){
			swaggerProperties.setDescription("解决了springfox用注解污染代码的问题，采用原生java-doc来实现文档的生成，让代码更加干净，学习成本更低");
		}
		if(StringUtils.isBlank(swaggerProperties.getVersion())){
			swaggerProperties.setVersion("3.0");
		}
		if(null == swaggerProperties.getContact()){
			Contact contact = new Contact();
			contact.setName("luocheng");
			contact.setUrl("http://git.oschina.net/CloudALM/CloudSwagger");
			contact.setEmail("1950013600@qq.com");
			swaggerProperties.setContact(contact);
		}
		if(null == swaggerProperties.getLicense()){
			License license = new License();
			license.setName("Apache License, Version 2.0");
			license.setUrl("https://www.apache.org/licenses/LICENSE-2.0.html");
			swaggerProperties.setLicense(license);
		}
		return swaggerProperties;
	}
}
